<template>
  <el-form ref="formRef" :model="_form" :rules="rules" label-width="100px">
    <!-- <div v-if="!isAdd" class="top">
      <div class="top-l">
        <el-form-item label-width="0">
          <hold-upload
            :key="uploadKey"
            list-type="picture"
            :file-list="[]"
            :limit="1"
            file-name="headPhoto"
            file-type=".png,.jpg,.jpeg"
            :show-file-list="false"
            :avatar-url="_form.headPhoto ? formatUrl(_form.headPhoto) : ''"
            @success="handleSuccess"
          />
        </el-form-item>
      </div>
    </div> -->
    <el-form-item label="登录账号" class="account-item" prop="account">
      <el-input v-model="_form.account" :disabled="!isAdd" placeholder="请输入登录账号" />
    </el-form-item>
    <el-form-item v-if="isAdd" label="密码" prop="password">
      <el-input v-model="_form.password" show-password type="password" placeholder="请输入密码" />
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="_form.name" placeholder="请输入姓名" />
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model.trim="_form.phone" placeholder="请输入手机号" />
    </el-form-item>
    <el-form-item label="所属机构" prop="oid">
      <el-select v-model="_form.oid" placeholder="请选择所属机构" filterable>
        <el-option
          v-for="item in orgOptions"
          :key="item.oid"
          :label="item.name"
          :value="item.oid"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="系统权限" prop="roleDefId">
      <el-select v-model="_form.roleDefId" placeholder="请选择系统权限" clearable filterable>
        <el-option
          v-for="item in roleData.sysRole"
          :key="item.rid"
          :label="item.name"
          :value="item.rid"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="用户角色" prop="roleId">
      <el-select v-model="_form.roleId" placeholder="请选择用户角色" clearable filterable>
        <el-option
          v-for="item in roleData.defRole"
          :key="item.rid"
          :label="item.name"
          :value="item.rid"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model.trim="_form.email" placeholder="请输入邮箱" />
    </el-form-item>
    <el-form-item label="性别" prop="gender">
      <el-select v-model="_form.gender" placeholder="性别" clearable>
        <el-option
          v-for="item in sexOptions"
          :key="item.code"
          :label="item.value"
          :value="item.code"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="出生日期" prop="birthday">
      <el-date-picker
        style="width: 100%"
        v-model="_form.birthday"
        value-format="YYYY-MM-DD"
        type="date"
        placeholder="选择日期"
        :disabled-date="disabledDate"
      />
    </el-form-item>

    <el-form-item label="所属部门" prop="did">
      <el-select v-model="_form.did" placeholder="请选择所属部门" clearable filterable>
        <el-option
          v-for="item in depOptions"
          :key="item.did"
          :label="item.name"
          :value="item.did"
        />
      </el-select>
    </el-form-item>
    <!-- <el-form-item label="角色" prop="roleId">
      <el-select v-model="_form.roleId" placeholder="请选择角色" clearable filterable>
        <el-option
          v-for="item in roleData.defRole"
          :key="item.rid"
          :label="item.name"
          :value="item.rid"
        />
      </el-select>
    </el-form-item> -->

    <!-- 后面加 -->
    <!-- <el-form-item label="身份证号" prop="idNo">
      <el-input v-model.trim="_form.idNo" maxlength="18" placeholder="请输入身份证号" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model.trim="_form.email" placeholder="请输入邮箱" />
    </el-form-item>
    <el-form-item label="籍贯" prop="birthplace">
      <el-input v-model="_form.birthplace" placeholder="请输入籍贯" />
    </el-form-item>
    <el-row>
      <el-col :span="12">
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="_form.birthday"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="性别" prop="gender">
          <el-select v-model="_form.gender" placeholder="性别" clearable>
            <el-option
              v-for="item in sexOptions"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="学历" prop="education">
          <el-select v-model="_form.education" clearable filterable placeholder="请选择学历">
            <el-option
              v-for="item in sexOptions"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="毕业院校" prop="school">
          <el-input v-model="_form.school" placeholder="请输入毕业院校" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="专业" prop="major">
          <el-input v-model="_form.major" placeholder="请输入专业" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="参加工作时间" prop="joinIn">
          <el-date-picker
            v-model="_form.joinIn"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="岗位" prop="jobPost">
          <el-select v-model="_form.jobPost" clearable filterable placeholder="请选择岗位">
            <el-option
              v-for="item in sexOptions"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="职称" prop="title">
          <el-select v-model="_form.title" clearable filterable placeholder="请选择职称">
            <el-option
              v-for="item in sexOptions"
              :key="item.code"
              :label="item.value"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="擅长" prop="speciality">
      <el-input v-model="_form.speciality" type="textarea" placeholder="请输入擅长" rows="4" />
    </el-form-item>
    <el-form-item label="个人简介" prop="intro">
      <el-input v-model="_form.intro" type="textarea" placeholder="请输入擅长" rows="4" />
    </el-form-item>
    <el-row>
      <el-col :span="12">
        <el-form-item label="签名" prop="signature">
          <HoldUpload
            :key="uploadKey"
            class="signature-upload"
            list-type="picture"
            :limit="1"
            file-name="headPhoto"
            file-type=".png,.jpg,.jpeg"
            need-tip
            :show-file-list="false"
            :head-photo="formatUrl(_form.signature)"
            @success="() => console.log('11')"
          />
        </el-form-item>
      </el-col>
    </el-row> -->
  </el-form>
</template>

<script lang="ts" setup>
import {
  computed,
  defineEmits,
  defineExpose,
  defineProps,
  PropType,
  reactive,
  ref,
  toRefs,
  watch,
} from 'vue'

import HoldUpload from '@/components/Upload/index.vue'

import DepApi from '@/api/backend/dep'

// import GroupApi from '@/api/backend/group'
import { useUserStore } from '@/store/user'

import { formatUrl } from '@/utils/common/formatUrl'
import { validate } from '@/utils/formExtend'
import { commonAccountReg, commonContactReg, emailReg, phoneReg } from '@/utils/regExp'

import IBaseObj from '#/index'

// const { userInfo, updateUserInfo } = useUserStore()

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

const _form: IBaseObj = reactive({
  account: '',
  address: '',
  birthday: '',
  birthplace: '',
  edu: '',
  email: '',
  gender: '',
  headIcon: '',
  idNo: '',
  intro: '',
  job: '',
  jobValue: '',
  joinIn: '',
  major: '',
  name: '',
  password: '',
  phone: '',
  roleDefId: '',
  roleId: '',
  school: '',
  signature: '',
  speciality: '',
  title: '',
  titleValue: '',
})
const rules = {
  // groups: [
  //   {
  //     type: 'array',
  //     required: true,
  //     message: '请选择组',
  //     trigger: 'change'
  //   }
  // ],
  roleDefId: [{ required: true, message: '请选择系统权限', trigger: 'change' }],
  // roleId: [{ required: true, message: '请选择用户角色', trigger: 'change' }],
  oid: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
  // role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  account: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { max: 20, message: '输入长度超过20个字符', trigger: 'blur' },
    {
      ...commonAccountReg,
      trigger: 'blur',
    },
    // { validator: checkloginCode, trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: 'blur',
    },
    { max: 20, message: '输入长度超过20个字符', trigger: 'blur' },
    {
      pattern: commonContactReg.pattern,
      message: commonContactReg.message,
      trigger: 'blur',
    },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { ...phoneReg, trigger: 'blur' },
    // { validator: checkPhone, trigger: 'blur' }
  ],
  email: [
    // { required: true, message: '请输入邮箱', trigger: 'blur' },
    { ...emailReg, trigger: 'blur' },
    // { validator: checkEmail, trigger: 'blur' }
  ],
}

// const sexOptions = [
//   {
//     name: '男',
//   },
//   {
//     name: '女',
//   },
// ]

const props = defineProps({
  form: {
    type: Object,
    default: () => {},
  },
  isAdd: {
    type: Boolean,
    default: true,
  },
  roleData: {
    type: Object,
    default: () => {
      return {
        sysRole: [],
        defRole: [],
      }
    },
  },
  orgOptions: {
    type: Array as PropType<IBaseObj[]>,
    default: () => [],
  },
  sexOptions: {
    type: Array as PropType<IBaseObj[]>,
    default: () => [],
  },
})

// const emits = defineEmits(['update:form', 'cancel', 'confirm'])

// const _form = computed({
//   get() {
//     return props.form
//   },
//   set() {
//     emits('update:form')
//   },
// })

const state: IBaseObj = reactive({
  uploadKey: +new Date(),
  groupOptions: [],
  currentHeadPhoto: '',
  depOptions: [],
})

const { uploadKey, depOptions } = toRefs(state)

watch(
  () => props.isAdd,
  (val) => {
    if (!val) {
      state.currentHeadPhoto = _form.headPhoto
    }
  },
  {
    immediate: true,
  }
)

// watch(
//   () => _form.value.oid,
//   async (val) => {
//     state.depOptions = []
//     if (val) {
//       // 查找该机构下的部门
//       const ret = await DepApi.getDepListByOid(val)
//       state.depOptions = ret || []
//       if (props.isAdd) {
//         if (state.depOptions.length > 0) {
//           _form.value.did = state.depOptions[0].did
//         }
//       }
//     }
//   },
//   {
//     immediate: true,
//   }
// )

// const getGroupData = async () => {
//   const ret = await GroupApi.getGlobalGroups()
//   state.groupOptions = ret.data || []
// }
// getGroupData()

const formRef = ref()

const valid = () => validate(formRef.value)
const clear = () => {
  formRef.value.resetFields()
  state.currentHeadPhoto = ''
  delete _form.uid
}

const handleSuccess = (file: any) => {
  _form.headPhoto = file.file.prepareData
}

// const updateInfo = () => {
//   // 如果创建的是本人的
//   if (_form.value.uid === userInfo.uid) {
//     const currentInfo = { ...userInfo }
//     currentInfo.headPhoto = _form.value.headPhoto
//     updateUserInfo(currentInfo)
//   }
// }

defineExpose({
  clear,
  valid,
  form: _form,
})
</script>

<style lang="scss" scoped>
.role-item {
  .el-select {
    width: 100% !important;
  }
}

.top {
  display: flex;
  justify-content: center;
  width: 100%;

  &-l {
    :deep(.el-form-item__content) {
      width: auto;
    }
  }

  &-r {
    margin-left: 10px;
    color: white;
    flex: 1;

    :deep(.el-form-item) {
      width: 100%;

      .el-form-item__content {
        width: auto;
      }
    }
  }
}

.avatar-uploader {
  :deep() {
    .el-upload {
      width: 200px;
      height: 60px;
      line-height: 60px;
    }
  }
}
</style>
